package com.demo.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.demo.gulimall.common.to.es.ProductEsTo;
import com.demo.gulimall.search.config.MallElasticSearchConfig;
import com.demo.gulimall.search.constant.EsConstant;
import com.demo.gulimall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.*;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Chen Yuan
 * @create 2023-05-29  14:53
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

	@Autowired
	private RestHighLevelClient restHighLevelClient;

	@Override
	public Boolean productStatusUp(List<ProductEsTo> productEsTos) throws IOException {
		// 将数据存到 ES

		// 1. 在 ES 创建索引, product

		// 2. 批量保存数据
		BulkRequest bulkRequest = new BulkRequest();
		for (ProductEsTo product : productEsTos) {
			IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX); // 指定索引
			indexRequest.id(product.getSkuId().toString()); // 指定ID
			indexRequest.source(JSON.toJSONString(product), XContentType.JSON); // 使用 JSON 格式传入数据
			bulkRequest.add(indexRequest);
		}
		BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, MallElasticSearchConfig.COMMON_OPTIONS);

		// 获取出错数据, 进行相应操作
		boolean hasFailures = bulk.hasFailures();
		List<String> errorProductIds = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());

		if (hasFailures) {
			log.error("-- 商品上架出错 - errorProductIds:{}", JSON.toJSONString(errorProductIds));
		}
		log.info("-- 商品上架成功 - errorProductIds:{}", JSON.toJSONString(errorProductIds));

		return hasFailures;
	}
}
